use crate::boot::db;
use chrono::Utc;
use cron::Schedule;
use std::str::FromStr;
use std::time;

struct CronBean {
    pub s: Schedule,
    pub f: fn() -> (),
}

pub async fn cron_init() {
    let v = vec![
        CronBean {
            s: Schedule::from_str("13 */4 * * * *").unwrap(),
            f: db_test,
        },
        CronBean {
            s: Schedule::from_str("46 */5 * * * *").unwrap(),
            f: db_test2,
        },
    ];

    loop {
        // 休眠请使用该句
        tokio::time::sleep(time::Duration::from_millis(1000)).await;
        // 这里休眠千万不能使用下面这句，这句会堵塞整个tokio进程
        //thread::sleep(time::Duration::from_millis(1000));
        let date = Utc::now();
        //println!("当前时间:{}", date);

        for c in &v {
            if c.s.includes(date) {
                log::info!(">>>>>时间刚刚好:{}", Utc::now());
                (c.f)();
                log::info!("<<<<<时间刚刚好:{}", Utc::now());
            }
        }
    }
}

fn db_test() {
    log::info!("我是一个计划任务 1111111111111111111");
    tokio::task::spawn(async {
        if let Ok(v) = db::RB
            .fetch("select id from sys_organ where id = 4", vec![])
            .await
        {
            // 休眠请使用该句
            tokio::time::sleep(time::Duration::from_millis(3000)).await;
            // 这里休眠千万不能使用下面这句，这句会堵塞整个tokio进程
            //thread::sleep(time::Duration::from_millis(3000));

            log::debug!(" >>>>>>1111111>>>>>> 读取数据库成功:{}", v);
        } else {
            log::error!("{} ", "数据库连接失败！");
        }
    });
}

fn db_test2() {
    log::info!("我是一个计划任务 2222222222222222222222");
    tokio::task::spawn(async {
        if let Ok(v) = db::RB
            .fetch("select id from sys_organ where id = 4", vec![])
            .await
        {
            // 休眠请使用该句
            tokio::time::sleep(time::Duration::from_millis(3000)).await;
            // 这里休眠千万不能使用下面这句，这句会堵塞整个tokio进程
            //thread::sleep(time::Duration::from_millis(3000));

            log::debug!(" >>>>>2222222>>>>>>> 读取数据库成功:{}", v);
        } else {
            log::error!("{} ", "数据库连接失败！");
        }
    });
}
